package com.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.common.cache.GlobalLocalCache;
import com.knowledge.common.constant.GlobalConstant;
import com.knowledge.dao.entity.SysUser;
import com.knowledge.dao.entity.TokenEntity;
import com.knowledge.dao.mapper.TokenMapper;
import com.knowledge.listenter.event.CacheEvent;
import com.knowledge.service.TokenService;
import com.knowledge.utils.JwtUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户Token表 服务实现类
 * </p>
 *
 * @author zzz
 * @since 2022-03-05
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, TokenEntity> implements TokenService {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public String addToken(SysUser sysUser) {
        String tokenId = JwtUtil.createToken(sysUser.getId());
        //查询
        QueryWrapper<TokenEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", sysUser.getId());
        TokenEntity tokenEntity = getOne(queryWrapper);
        if (tokenEntity == null){
            tokenEntity = new TokenEntity();
            tokenEntity.setTokenId(tokenId);
            tokenEntity.setUserId(sysUser.getId());
            tokenEntity.setCreateTime(new Date());
            tokenEntity.setUpdateTime(new Date());
            tokenEntity.setExpireTime(new Date(System.currentTimeMillis() + GlobalConstant.EXPIRATION_TIME));
            save(tokenEntity);
        }else {
            UpdateWrapper<TokenEntity> updateWrapper = new UpdateWrapper();
            updateWrapper.lambda().set(TokenEntity::getTokenId, tokenId)
                    .set(TokenEntity::getExpireTime, new Date(System.currentTimeMillis() + GlobalConstant.EXPIRATION_TIME))
                    .eq(TokenEntity::getId, tokenEntity.getId());
            update(updateWrapper);
        }
        //本地缓存
        GlobalLocalCache.cache(tokenId, sysUser);
        applicationContext.publishEvent(new CacheEvent(this, sysUser.getId(), tokenId));
        return tokenId;
    }

    @Override
    public void removeToken(String tokenId) {
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setTokenId(tokenId);
        removeById(tokenEntity);
    }

    @Override
    public List<TokenEntity> listEffectiveToken() {
        QueryWrapper<TokenEntity> queryWrapper = new QueryWrapper();
        queryWrapper.ge("expire_time", new Date());
        return list(queryWrapper);
    }
}
